<?php


namespace app\astrologer\controller\v6;

use app\astrologer\controller\AstrAuth;
use app\astrologer\controller\Upload;
use app\common\cachemodel\ZhunleAstrWithdrawalRecord;
use app\common\cachemodel\ZlcrAstrAccount;
use app\common\cachemodel\ZlcrAstrAccountRecord;
use app\common\cachemodel\ZlcrAstrInfo;
use app\common\lib\Util;
use app\common\model\User;
use app\zyhsapi\model\ZyhsUser;
use think\Db;
use think\Env;
use think\Log;
use think\response\Json;

class Earnings extends AstrAuth
{
    protected $startDay = 5;
    protected $endDay = 28;

    /**
     * 获取列表数据
     * @method GET
     */
    public function list2()
    {
        $param['page'] = $this->request->param('page/d', 1);
        $param['limit'] = $this->request->param('limit/d', 10);

        $astrId = $this->astrInfo['id'];
        $pageData = (new ZlcrAstrAccountRecord())->where(['astr_id' => $astrId, 'type' => ['in', [1, 4, 5, 6]]])->order('create_time desc')
            ->paginate(['page' => $param['page'], 'list_rows' => $param['limit']])->toArray();

        $qidData = [];
        foreach ($pageData['data'] as $key => $datum)
        {
            switch ($datum['question_type'])
            {
                case 1:
                case 2:
                case 4:
                    $qidData[$datum['question_type']][] = $datum['qid'];
                    break;
                case 3:
                case 5:
                    $qidData[3][] = $datum['gid'];
                    break;
                case 6: //  准了-连线咨询 打赏
                    $qidData[6][] = $datum['gid'];
                    break;
                case 7: //  准有好事-连线咨询 打赏
                    $qidData[7][] = $datum['gid'];
                    break;
            }
        }
        // 1=>定制报告 2=>问答 3=>连线咨询 4=>准有好事-问答
        $questionInfo1 = [];
        if (isset($qidData[1]) && $qidData[1])
        {
            $questionInfo1 = Db::table('wechat_backup_07_18_14_43_00.zlcr_custom_report_question')->where(['id' => ['in', $qidData[1]]])->column('question_name,astr_receiving_time,is_merge,qtype,answer_time,check_time2', 'id');
        }
        $questionInfo2 = [];
        if (isset($qidData[2]) && $qidData[2])
        {   // 问答
            $questionInfo2 = Db::table('wechat_backup_07_18_14_43_00.zlcr2_user_question')->where(['id' => ['in', $qidData[2]]])->column('*', 'id');
        }
        $questionInfo3 = [];
        if (isset($qidData[3]) && $qidData[3])
        {   // 连线咨询
            $questionInfo3 = Db::table('good_wechat.zyhs_consult_chat_rtc_record')->where(['id' => ['in', $qidData[3]]])->column('*', 'id');
        }
        $questionInfo4 = [];
        if (isset($qidData[4]) && $qidData[4])
        {   // 准有好事 - 问答
            $questionInfo4 = Db::table('good_wechat.zyhs_astr_tasks')->alias('t')
                ->join('good_wechat.zyhs_user_question q', 'q.id=t.qid')->where(['t.id' => ['in', $qidData[4]]])->column('q.question,q.id qid,q.question_type,t.create_time astr_receiving_time,q.is_synastry,t.status,t.lock_reason', 't.id');
        }
        $questionInfo6 = [];
        if (isset($qidData[6]) && $qidData[6])
        {   // 准了-连线咨询 打赏
            $questionInfo6 = Db::table('wechat_backup_07_18_14_43_00.zhunle_user_account_record')->where(['id' => ['in', $qidData[6]]])->column('*', 'id');
        }
        $questionInfo7 = [];
        if (isset($qidData[7]) && $qidData[7])
        {   // 准有好事-连线咨询 打赏
            $questionInfo7 = Db::table('good_wechat.zyhs_user_account_record')->where(['id' => ['in', $qidData[7]]])->column('*', 'id');
        }
        $dataList = [];
        $userInfoList = [];
        $zyhsUserInfoList = [];
        foreach ($pageData['data'] as $key => $datum)
        {
            $itemInfo = null;
            switch ($datum['question_type'])
            {
                case 1:
                    $itemInfo = $questionInfo1[$datum['qid']] ?? null;
                    break;
                case 2:
                    $itemInfo = $questionInfo2[$datum['qid']] ?? null;
                    break;
                case 3:
                case 5:
                    $itemInfo = $questionInfo3[$datum['gid']] ?? null;
                    break;
                case 4:
                    $itemInfo = $questionInfo4[$datum['qid']] ?? null;
                    break;
                case 6: // 准了-连线咨询 打赏
                    $itemInfo = $questionInfo6[$datum['gid']] ?? null;
                    $itemInfo['extend'] = json_decode($itemInfo['extend'], true);
                    break;
                case 7: // 准有好事-连线咨询 打赏
                    $itemInfo = $questionInfo7[$datum['gid']] ?? null;
                    break;
            }
            if (!$itemInfo)
            {
                continue;
            }

            switch ($datum['question_type'])
            {
                case 1: // 准了 - 定制报告
                    $dataList[] = [
                        'task_id' => (string)$datum['qid'],
                        'qid' => (string)$datum['qid'],
                        'question_type' => 4,
                        'question' => $itemInfo['question_name'],
                        'astr_receiving_time' => (int)$itemInfo['astr_receiving_time'],
                        'create_time' => (int)$datum['create_time'],
                        'earnings' => $datum['amount'],
                        'status_des' => '完成任务',
                        'status_color' => '#00D8D3',
                        'proportion' => $datum['proportion'],
                        'is_merge' => (int)($itemInfo['is_merge'] ?? 0),
                        'qtype' => (int)$itemInfo['qtype'],
                        'answer_time' => (int)$itemInfo['answer_time'],
                        'check_time2' => (int)$itemInfo['check_time2'],
                        'app_type' => 1,
                    ];
                    break;
                case 2: // 准了 - 问答
                    $dataList[] = [
                        'task_id' => (string)Db::table('wechat_backup_07_18_14_43_00.zlcr2_astr_tasks')->where(['astr_id' => $this->astrInfo['id'], 'qid' => $datum['qid']])->value('id'),
                        'qid' => (string)$datum['qid'],
                        'question_type' => (int)$itemInfo['question_type'],
                        'question' => $itemInfo['question'],
                        'astr_receiving_time' => (int)$itemInfo['astr_receiving_time'],
                        'create_time' => (int)$datum['create_time'],
                        'earnings' => $datum['amount'],
                        'status_des' => $itemInfo['lock_reason'] ? '扣除收益：' . $itemInfo['lock_reason'] : '完成任务',
                        'status_color' => $itemInfo['lock_reason'] ? '#FFB500' : '#00D8D3',
                        'proportion' => $datum['proportion'],
                        'is_merge' => (int)($itemInfo['is_synastry'] ?? 0),
                        'qtype' => 0,
                        'answer_time' => 0,
                        'check_time2' => 0,
                        'app_type' => 1,
                    ];
                    break;
                case 3: // 准有好事 - 连线咨询
                case 5: // 准了 - 连线咨询
                    $appType = (int)($itemInfo['app_type'] ?? 1); // 1=>准有好事  2=>准了APP
                    $dataList[] = [
                        'task_id' => (string)$itemInfo['chat_detail_id'],
                        'qid' => (string)$itemInfo['chat_detail_id'],
                        'question_type' => 5,
                        'question' => '计价时长：' . (Util::secondToMinute($itemInfo['eff_duration'])) . '(单价：' . ($itemInfo['unit_price'] / 10 * $datum['proportion']) . "元/分钟)",
                        'astr_receiving_time' => '',
                        'create_time' => (int)$datum['create_time'],
                        'earnings' => $datum['amount'],
                        'status_des' => $datum['status'] == 1 ? '完成任务' : '操作纠正，收益扣除',
                        'status_color' => '#00D8D3',
                        'proportion' => $datum['proportion'],
                        'is_merge' => 0,
                        'qtype' => 0,
                        'answer_time' => 0,
                        'check_time2' => 0,
                        'app_type' => $appType === 1 ? 2 : 1,   // 1=>准了 2=>准有好事
                    ];
                    break;
                case 4: // 准有好事 - 问答
                    $statusDes = '完成任务';
                    $statusColor = '#00D8D3';
                    if ($datum['type'] == 4)
                    {
                        $statusDes = '扣除收益';
                        if ($itemInfo['lock_reason'])
                        {
                            $statusDes .= '：' . $itemInfo['lock_reason'];
                        }
                        $statusColor = '#FFB500';

                        $datum['amount'] = '-' . $datum['amount'];
                    }
                    if ($datum['type'] == 5)
                    {
                        $statusDes = '完成任务';
                    }

                    $dataList[] = [
                        'task_id' => (string)$itemInfo['id'],
                        'qid' => (string)$itemInfo['qid'],
                        'question_type' => (int)$itemInfo['question_type'],
                        'question' => $itemInfo['question'],
                        'astr_receiving_time' => (int)$itemInfo['astr_receiving_time'],
                        'create_time' => (int)$datum['create_time'],
                        'earnings' => $datum['amount'],
                        'status_des' => $statusDes,
                        'status_color' => $statusColor,
                        'proportion' => $datum['proportion'],
                        'is_merge' => (int)($itemInfo['is_synastry'] ?? 0),
                        'qtype' => 0,
                        'answer_time' => 0,
                        'check_time2' => 0,
                        'app_type' => 2,
                    ];
                    break;
                case 6: // 准了-连线咨询 打赏
                    if (isset($userInfoList[$itemInfo['uid']]))
                    {
                        $nickname = $userInfoList[$itemInfo['uid']]['nickname'];
                    } else
                    {
                        $userInfo = (new User())->getUserinfo(['id' => $itemInfo['uid']]);
                        $nickname = $userInfo['nickname'];
                        $userInfoList[$itemInfo['uid']] = [
                            'nickname' => $nickname,
                        ];
                    }
                    $dataList[] = [
                        'task_id' => $nickname,
                        'qid' => '',
                        'question_type' => 6, //  1=>问答星盘 2=>问答骰子 3=>问答塔罗 4=>定制报告 5=>连线咨询 6=>连线咨询打赏
                        'question' => sprintf("%sx%d", $itemInfo['extend']['gift_name'], $itemInfo['extend']['num']),
                        'astr_receiving_time' => 0,
                        'create_time' => (int)$datum['create_time'],
                        'earnings' => $datum['amount'],
                        'status_des' => '',
                        'status_color' => '',
                        'proportion' => $datum['proportion'],
                        'is_merge' => 0,
                        'qtype' => 0,
                        'answer_time' => 0,
                        'check_time2' => 0,
                        'app_type' => 1,
                    ];
                    break;
                case 7: // 准有好事-连线咨询 打赏
                    if (isset($zyhsUserInfoList[$itemInfo['uid']]))
                    {
                        $nickname = $zyhsUserInfoList[$itemInfo['uid']]['nickname'];
                    } else
                    {
                        $userInfo = (new ZyhsUser())->getInfoById($itemInfo['uid']);
                        $nickname = $userInfo['nickname'];
                        $zyhsUserInfoList[$itemInfo['uid']] = [
                            'nickname' => $nickname,
                        ];
                    }
                    $dataList[] = [
                        'task_id' => $nickname,
                        'qid' => '',
                        'question_type' => 6, //  1=>问答星盘 2=>问答骰子 3=>问答塔罗 4=>定制报告 5=>连线咨询 6=>连线咨询打赏
                        'question' => sprintf("%sx%d", $itemInfo['extend']['gift_name'], $itemInfo['extend']['num']),
                        'astr_receiving_time' => 0,
                        'create_time' => (int)$datum['create_time'],
                        'earnings' => $datum['amount'],
                        'status_des' => '',
                        'status_color' => '',
                        'proportion' => $datum['proportion'],
                        'is_merge' => 0,
                        'qtype' => 0,
                        'answer_time' => 0,
                        'check_time2' => 0,
                        'app_type' => 2,
                    ];
                    break;
            }
        }

        $pageData['data'] = $dataList;

        $pageData['header_info'] = $this->getWithdrawalHeaderInfo($this->astrInfo['id'], 1);

        return show(200, '请求成功', $pageData);
    }

    /**
     * 提交/取消 提现申请
     * @return Json
     */
    public function applyWithdraw()
    {
        $type = input('type/d', 0);
        $invoiceUrl = input('invoice_path/s', '');
        $id = input('id/d', 0);
        // 开票 信息
        $purchaserName = '北京星座女神文化传媒有限公司';
        $purchaserRegisterNum = '911101053181974480';

        if (!in_array($type, [0, 1], true))
        {
            return show(config('code.error'), '请求异常，请稍后重试');
        }

        if (Util::commentCheck($this->astrInfo['id'], ['applyWithdraw', 'type' => $type, 'invoiceUrl' => $invoiceUrl, 'id' => $id], 5))
        {
            return show(config('code.error'), '操作频繁，请稍后再试～');
        }
        if ($type === 1)
        {   // 申请 开票
            if (empty($invoiceUrl))
            {
                return show(config('code.error'), '请上传发票');
            }
            if ((new ZhunleAstrWithdrawalRecord())->where(['astr_id' => $this->astrInfo['id'], 'type' => 1, 'is_remit' => 0, 'check_status' => ['in', [0, 1]]])->count())
            {
                return show(config('code.error'), '正在申请提现中，操作失败');
            }
            $day = (int)date('d');
            if ($day < $this->startDay || $day > $this->endDay)
            {   // 未到提现日期
                return show(config('code.error'), '未到提现日暂不支持提现');
            }
            // 准了 - 可提现金额
            $withdrawalAmount = Db::table('wechat_backup_07_18_14_43_00.zlcr_astr_account_withdrawal_record')
                ->where(['astr_id' => $this->astrInfo['id'], 'type' => 1, 'wid' => 0, 'is_withdrawal' => 0, 'is_emergency' => 0])
                ->field('astr_earnings,excluding_earning2,astr_earnings3,id,date')->select();

            $list = [];
            $totalWithdrawalAmount = 0;
            foreach ($withdrawalAmount as $datum)
            {   // $datum['astr_earnings'] 收益金额不包括 私域收入
                $totalWithdrawalAmount = $totalWithdrawalAmount + $datum['astr_earnings'] - $datum['excluding_earning2'] + $datum['astr_earnings3'];
                $list['zhunle'][] = [
                    'id' => (int)$datum['id'],
                    'date' => (int)$datum['date'],
                    'des' => date('Y年m月', strtotime($datum['date'])),
                ];
            }
            // 共 可提现 金额
            $priAstrId = (new ZlcrAstrInfo())->getPrivateAstrId($this->astrInfo['id']);
            if ($priAstrId)
            {   // 有 私域 账号
                $privateWithdrawalAmount = Db::table('wechat_backup_07_18_14_43_00.private_astr_withdrawal_record')
                    ->where(['astr_id' => $priAstrId, 'wid' => 0, 'is_withdrawal' => 0, 'date' => ['>', 20231201]])
                    ->field('astr_earnings,excluding_earning,id,date')->select();
                foreach ($privateWithdrawalAmount as $datum)
                {   // 累加 私域 可提现金额 - 私域扣减金额
                    $totalWithdrawalAmount = $totalWithdrawalAmount + $datum['astr_earnings'] - $datum['excluding_earning'];
                    $list['siyu'][] = [
                        'id' => (int)$datum['id'],
                        'date' => (int)$datum['date'],
                        'des' => date('Y年m月', strtotime($datum['date'])),
                    ];
                }
            }

            if ($totalWithdrawalAmount < 100)
            {
                return show(config('code.error'), '当前可提现金额不足100，请联系客服');
            }

            if (Env::get('host.name') === 'online')
            {   // 线上才进行校验
                $res = Util::aliInvoiceOcr($invoiceUrl);
                if ($res['code'] != 200)
                {
                    Log::write('返回给用户：发票识别失败，请重新上传；发票Ocr识别：' . json_encode($res, JSON_UNESCAPED_UNICODE), 'error', true);
                    return show(config('code.error'), $res['msg'] ?? '发票识别失败，请重新上传');
                }
                //两位小数对比，下面这种方法对比失败
                //$sub = $res['data']['amountInFiguers'] - $totalWithdrawalAmount;
                // 设置bcmath函数所使用的小数点位数和进制
                bcscale(2);
                // 高精度减法
                $sub = bcsub($res['data']['amountInFiguers'], $totalWithdrawalAmount);
                if ($sub < 0)
                {
                    return show(config('code.error'), '发票金额不足可提现金额，请重新上传');
                }
                if ($res['data']['purchaserRegisterNum'] !== $purchaserRegisterNum)
                {
                    return show(config('code.error'), '发票购买方信息错误，请重新上传');
                }
                if ($res['data']['purchaserName'] !== $purchaserName)
                {
                    return show(config('code.error'), '发票购买方信息错误，请重新上传');
                }
                // $res['data']['amountInFiguers']          含税金额
                // $res['data']['invoiceCode']              发票代码
                // $res['data']['invoiceNum']               发票号码
                // $res['data']['invoiceDate']              开票日期 格式YYYYMMDD
                // $res['data']['checkCode']                校验码 【注意：专票、全电票可不传，其他必填。校验码支持全位和后6位】
                // $res['data']['totalAmount']              不含税金额 【注意：普票可不传，其他发票必填 。全电票请传含税金额，其他发票需传 不含税金额】

                // $res['data']['purchaserRegisterNum']     购买方 纳税人识别号
                // $res['data']['purchaserName']            购买方 公司名称
                if (in_array($res['data']['invoiceType'], ['电子发票(普通发票)', '电子发票(专用发票)'], true))
                {   // 全电发票 全电票请传含税金额
                    $bhsje = $res['data']['amountInFiguers'];
                } else
                {   // 不含税金额
                    $bhsje = $res['data']['totalAmount'];
                }
                /**
                 * 发票 查验
                 * @param string $fpdm 发票代码 【注意：全电票可不传，其他必传】
                 * @param string $fphm 发票号码
                 * @param string $kprq 开票日期 格式YYYYMMDD
                 * @param string $xym 校验码 【注意：专票、全电票可不传，其他必填。校验码支持全位和后6位】
                 * @param string $bhsje 不含税金额 【注意：普票可不传，其他发票必填 。全电票请传含税金额，其他发票需传 不含税金额】
                 * @return array
                 */
                $checkRes = Util::aliIinvoiceCheck($res['data']['invoiceCode'], $res['data']['invoiceNum'], $res['data']['invoiceDate'], $res['data']['checkCode'], $bhsje);
                if ($checkRes['code'] != 200 || $checkRes['data']['result'] != 1)
                {
                    Log::write('发票查验失败：' . json_encode($checkRes, JSON_UNESCAPED_UNICODE), 'error', true);
                    $msg = '发票识别失败，请重新上传';
                    //返回数据样例
                    //{"data":[],"msg":"超过该张>票当天查验次数","success":false,"code":203,"taskNo":"040151087236290063104889"}
                    //{"data":{"result":3,"message":"查无此票"},"msg":"成功","success":true,"code":200,"taskNo":"376752828202630827640447"}
                    if (isset($checkRes['data']) && isset($checkRes['data']['message']))
                    {//data里面存在 message，直接取 message
                        if (isset($checkRes['data']['result']) && (int)$checkRes['data']['result'] === 3 && $checkRes['data']['message'] === '查无此票')
                        {
                            $msg = '查无此票，税务系统有延时，建议您开票后，等待1小时，再上传发票！';
                        } else
                        {
                            $msg = $checkRes['data']['message'];
                        }
                    } else
                    {//data为空，那么取外层的msg
                        $msg = $checkRes['msg'];
                    }
                    return show(config('code.error'), $msg);
                }
                if ($checkRes['data']['info']['buyerTaxNo'] !== $purchaserRegisterNum)
                {
                    return show(config('code.error'), '发票购买方信息错误，请重新上传');
                }
                if ($checkRes['data']['info']['buyerName'] !== $purchaserName)
                {
                    return show(config('code.error'), '发票购买方信息错误，请重新上传');
                }
                //两位小数对比，下面这种方法对比失败
                //$sub2 = $checkRes['data']['info']['totalAmount'] - $totalWithdrawalAmount;
                // 设置bcmath函数所使用的小数点位数和进制
                bcscale(2);
                // 高精度减法
                $sub2 = bcsub($checkRes['data']['info']['totalAmount'], $totalWithdrawalAmount);
                if ($sub2 < 0)
                {
                    return show(config('code.error'), '发票金额不足可提现金额，请重新上传');
                }
            }
            $incomeTax = Util::CalculationTaxRate($totalWithdrawalAmount);
            $nowTime = time();
            $astrWithdrawalData = [
                'astr_id' => $this->astrInfo['id'],
                'type' => 1,
                'withdrawal_amount' => $totalWithdrawalAmount,  // 提现金额
                'income_tax' => $incomeTax,
                'after_tax_income' => $totalWithdrawalAmount - $incomeTax,
                'invoice_url' => $invoiceUrl,
                'invoice_check_data' => json_encode($checkRes ?? [], JSON_UNESCAPED_UNICODE), // 发票查验数据
                'list' => json_encode($list, JSON_UNESCAPED_UNICODE),   // 流水来源
                'create_time' => $nowTime,
                'create_date' => date('Ym', $nowTime),
            ];

            $id = (new ZhunleAstrWithdrawalRecord())->SaveData($astrWithdrawalData);

            if ($id)
            {
                return show(config('code.success'), '申请提现成功');
            } else
            {
                return show(config('code.error'), '服务异常，请稍后再试');
            }
        } else
        {   // 取消 申请开票
            if (!$id)
            {
                return show(config('code.error'), '请求异常，请稍后重试');
            }

            try
            {
                $data = (new ZhunleAstrWithdrawalRecord())->where(['id' => $id, 'type' => 1, 'astr_id' => $this->astrInfo['id']])->findOrFail()->toArray();
                if ($data['is_remit'])
                {
                    return show(config('code.error'), '提现申请状态异常，操作失败');
                }
                if ($data['check_status'] == 1)
                {
                    return show(config('code.error'), '已通过审核，无法取消');
                }
                if ($data['check_status'] == 2)
                {
                    return show(config('code.error'), '审核未通过，已经自动取消了');
                }
                if ($data['check_status'] == 3)
                {
                    return show(config('code.error'), '已经取消了，请勿重复操作');
                }

                (new ZhunleAstrWithdrawalRecord())->where(['id' => $id])->update(['check_status' => 3, 'check_time' => $this->request->time()]);

                return show(config('code.success'), '提现申请取消成功');
            }
            catch (\Exception $e)
            {
                return show(config('code.error'), '服务异常，请稍后重试');
            }
        }
    }

    /**
     * 提现历史列表
     * @return Json
     */
    public function getWithdrawHistoryList()
    {
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);

        $pageData = (new ZhunleAstrWithdrawalRecord())->where(['type' => 1, 'astr_id' => $this->astrInfo['id']])
            ->order('id desc')
            ->paginate(['page' => $page, 'list_rows' => $limit])->toArray();

        $dataList = [];
        foreach ($pageData['data'] as $itemData)
        {
            $desList = [
                [
                    'title' => '申请提现金额：',
                    'des_info' => [
                        'content' => $itemData['withdrawal_amount'] . '元',
                        'color' => '#24252A',
                    ],
                ], [
                    'title' => '申请日期：',
                    'des_info' => [
                        'content' => date('Y年m月d日 H:i', $itemData['create_time']),
                        'color' => '#24252A',
                    ],
                ], [
                    'title' => '扣除个税金额：',
                    'des_info' => [
                        'content' => $itemData['income_tax'] . '元',
                        'color' => '#24252A',
                    ],
                ], [
                    'title' => '实际到账金额：',
                    'des_info' => [
                        'content' => $itemData['after_tax_income'] . '元',
                        'color' => '#24252A',
                    ],
                ],
            ];

            if ($itemData['is_remit'] == 1)
            {
                $desList[] = [
                    'title' => '打款时间：',
                    'des_info' => [
                        'content' => date('Y年m月d日 H:i', $itemData['remit_time']),
                        'color' => '#24252A',
                    ],
                ];
            }

            switch ($itemData['check_status'])
            {
                case 1: // 审核通过
                    if ($itemData['is_remit'] == 1)
                    {
                        $desList[] = [
                            'title' => '当前状态：',
                            'des_info' => [
                                'content' => '已打款',
                                'color' => '#00D8D3',
                            ],
                        ];
                    } else
                    {
                        $desList[] = [
                            'title' => '当前状态：',
                            'des_info' => [
                                'content' => '审核已通过等待打款中',
                                'color' => '#00D8D3',
                            ],
                        ];
                    }
                    break;
                case 2: // 审核未通过
                    $desList[] = [
                        'title' => '当前状态：',
                        'des_info' => [
                            'content' => '审核不通过',
                            'color' => '#FFB500',
                        ],
                    ];
                    $desList[] = [
                        'title' => '原因：',
                        'des_info' => [
                            'content' => $itemData['check_remark'],
                            'color' => '#24252A',
                        ],
                    ];
                    break;
                case 3: // 已取消
                    $desList[] = [
                        'title' => '当前状态：',
                        'des_info' => [
                            'content' => '申请已取消',
                            'color' => '#9FA1AA',
                        ],
                    ];
                    break;
                default: // 等待审核
                    $desList[] = [
                        'title' => '当前状态：',
                        'des_info' => [
                            'content' => '等待审核',
                            'color' => '#FFB500',
                        ],
                    ];
            }

            $dataList[] = [
                'invoice_url' => Env::get('host.domain') . '/web/agreement/astrologer_app_invoice_view.html?pdf_url=' . base64_encode(Upload::getOssPrivateUrl($itemData['invoice_url'])),
                'des_list' => $desList,
            ];
        }

        $pageData['list'] = $dataList;

        $pageData['header_info'] = $this->getWithdrawalHeaderInfo($this->astrInfo['id'], 1);

        return show(config('code.success'), '请求成功', $pageData);
    }

    private function getWithdrawalHeaderInfo(int $astrId, int $type = 1)
    {
        $accountInfo = (new ZlcrAstrAccount())->getAstrAccountInfo($astrId, ['balance', 'total_amount']);
        $balance = $accountInfo['balance']; // 当前余额
        // 准了 - 可提现金额
        $withdrawalAmount = Db::table('wechat_backup_07_18_14_43_00.zlcr_astr_account_withdrawal_record')
            ->where(['astr_id' => $astrId, 'type' => 1, 'wid' => 0, 'is_withdrawal' => 0, 'is_emergency' => 0])
            ->field('sum(astr_earnings) as earnings,sum(excluding_earning2) as excluding_earning2,sum(astr_earnings3) as astr_earnings3')->find();

        $withdrawalAmount = [
            'earnings' => $withdrawalAmount['earnings'] ?? 0,
            'excluding_earning2' => $withdrawalAmount['excluding_earning2'] ?? 0,
            'astr_earnings3' => $withdrawalAmount['astr_earnings3'] ?? 0,
        ];
        // 共 可提现 金额
        $totalWithdrawalAmount = $withdrawalAmount['earnings'] - $withdrawalAmount['excluding_earning2'] + $withdrawalAmount['astr_earnings3'];
        // 准了 可提现金额
        $zhunleWithdrawalAmount = $withdrawalAmount['earnings'] - $withdrawalAmount['excluding_earning2'];
        // 私域 - 可提现金额
        $siyuWithdrawalAmount = $withdrawalAmount['astr_earnings3'];
        $priAstrId = (new ZlcrAstrInfo())->getPrivateAstrId($astrId);
        if ($priAstrId)
        {   // 有 私域 账号
            $privateWithdrawalAmount = Db::table('wechat_backup_07_18_14_43_00.private_astr_withdrawal_record')
                ->where(['astr_id' => $priAstrId, 'wid' => 0, 'is_withdrawal' => 0, 'date' => ['>', 20231201]])
                ->field('sum(astr_earnings) as earnings,sum(excluding_earning) as excluding_earning')->find();
            // 私域 可提现金额
            $privateWithdrawalAmount = [
                'earnings' => $privateWithdrawalAmount['earnings'] ?? 0,
                'excluding_earning' => $privateWithdrawalAmount['excluding_earning'] ?? 0,
            ];
            $siyuWithdrawalAmount = $siyuWithdrawalAmount + $privateWithdrawalAmount['earnings'] - $privateWithdrawalAmount['excluding_earning'];
            // 累加 私域 可提现金额 - 私域扣减金额
            $totalWithdrawalAmount = $totalWithdrawalAmount + $privateWithdrawalAmount['earnings'] - $privateWithdrawalAmount['excluding_earning'];
            $dateList = [
                [
                    "",
                    "平台",
                    "私域",
                ], [
                    "可提现金额",
                    "{$zhunleWithdrawalAmount}",
                    "{$siyuWithdrawalAmount}",
                ], [
                    "账户余额",
                    "{$balance}",
                    "-",
                ],
            ];
        }
        // 获取当前 已申请 提现金额
        $withdrawalInfo = Db::table('wechat_backup_07_18_14_43_00.zhunle_astr_withdrawal_record')->where(['type' => 1, 'astr_id' => $astrId, 'check_status' => ['in', [0, 1]], 'is_remit' => 0])->field('withdrawal_amount,check_status,id,invoice_url')->find();
        $withdrawal = $withdrawalInfo['withdrawal_amount'] ?? 0; // 已申请提现
        $totalWithdrawalAmount = $totalWithdrawalAmount - $withdrawal;
        $totalWithdrawalAmount = max($totalWithdrawalAmount, 0); // 剩余可提现金额

        if ($type === 1)
        {
            return [
                'title' => "可提现金额：{$totalWithdrawalAmount}元",
                'des' => "账户余额：{$balance}元",
                'hint' => '展示的金额为税前收益，每月初结算后可在规定时间申请提现',
                'detail_list' => $dateList ?? [],
                'withdraw_hint' => '',
            ];
        } else
        {
            return [
                'totalWithdrawalAmount' => $totalWithdrawalAmount,  // 可提现 金额
                'balance' => $balance,  // 账户余额
                'zhunleWithdrawalAmount' => $zhunleWithdrawalAmount,    // 准了 提现金额
                'siyuWithdrawalAmount' => $siyuWithdrawalAmount,    // 私域提现金额
                'withdrawal' => $withdrawal,    // 当前提现金额
                'check_status' => (int)($withdrawalInfo['check_status'] ?? 0), // 提现审核状态 0:待审核 1:审核通过
                'wid' => (int)($withdrawalInfo['id'] ?? 0),
                'invoice_url' => $withdrawalInfo['invoice_url'] ?? '',
            ];
        }
    }

    /**
     * 获取提现信息
     * @return Json
     */
    public function getApplyWithdrawInfo()
    {
        $headerInfo = $this->getWithdrawalHeaderInfo($this->astrInfo['id'], 2);

        $data = (new ZhunleAstrWithdrawalRecord())->where(['type' => 1, 'astr_id' => $this->astrInfo['id'], 'is_remit' => 0, 'check_status' => ['in', [0, 1]]])->find();
        $rightBtnInfo = ['is_show' => 0, 'title' => '', 'target' => '', 'link' => '',];
        $cancelBtnInfo = ['is_show' => 0, 'title' => '', 'id' => 0,];
        if ($data)
        {   // 当前已有 申请提现 记录
            $rightBtnInfo = [
                'is_show' => 1,
                'title' => '查看发票',
                'target' => 'link',
                'link' => Env::get('host.domain') . '/web/agreement/astrologer_app_invoice_view.html?pdf_url=' . base64_encode(Upload::getOssPrivateUrl($data['invoice_url'])),
            ];
            $invoiceAmount = $data['withdrawal_amount'];
            if ($data['check_status'] == 1)
            {   // 审核通过
                $bottomBtnInfo = [
                    'is_show' => 1,
                    'title' => '审核通过等待打款中',
                    'is_apply_withdraw' => 0,
                ];
            } else
            {   // 待审核
                $bottomBtnInfo = [
                    'is_show' => 1,
                    'title' => '等待审核中',
                    'is_apply_withdraw' => 0,
                ];
                $cancelBtnInfo = [
                    'is_show' => 1,
                    'title' => '取消申请',
                    'id' => (int)$data['id'],
                ];
            }
        } else
        {   // 没有提现记录
            $day = (int)date('d');
            if ($headerInfo['totalWithdrawalAmount'] >= 100 && $day >= $this->startDay && $day <= $this->endDay)
            {
                $rightBtnInfo = [
                    'is_show' => 1,
                    'title' => '上传发票',
                    'target' => 'local',
                    'link' => 'upload',
                ];
                $bottomBtnInfo = [
                    'is_show' => 1,
                    'title' => '申请提交',
                    'is_apply_withdraw' => 1,
                ];
            } else
            {
                if ($day < $this->startDay || $day > $this->endDay)
                {
                    $bottomBtnInfo = [
                        'is_show' => 1,
                        'title' => '未到提现日暂不支持提现',
                        'is_apply_withdraw' => 0,
                    ];
                }
                if ($headerInfo['totalWithdrawalAmount'] < 100)
                {
                    $bottomBtnInfo = [
                        'is_show' => 1,
                        'title' => '提现金额不可少于100元',
                        'is_apply_withdraw' => 0,
                    ];
                }
            }
            $invoiceAmount = $headerInfo['totalWithdrawalAmount'];
        }

        $title = "可提现金额：{$headerInfo['totalWithdrawalAmount']}元";
        if ($headerInfo['withdrawal'] > 0)
        {   // 已申请 提现
            $title .= $headerInfo['check_status'] == 1 ? "\r\n审核通过等待打款金额：{$headerInfo['withdrawal']}元" : "\r\n正在审核提现金额：{$headerInfo['withdrawal']}元";
        }

        $resData = [
            'title' => $title,
            'right_btn_info' => $rightBtnInfo,
            'des_center' => $headerInfo['withdrawal'] > 0 ? '' : "开票金额：{$invoiceAmount}元",
            'invoice_des' => $headerInfo['withdrawal'] > 0 ? '' : "名称：北京星座女神文化传媒有限公司\r\n税号：9111 0105 3181 9744 80\r\n地址电话：北京市朝阳区高碑店乡金家村中街8号C-3009  010-85164828",
            'des_bottom' => "提现金额需要上传对应金额的发票才可提现；每月{$this->startDay}-{$this->endDay}日可提交提现申请，请务必阅读并理解下方信息。",
            'bottom_btn_info' => $bottomBtnInfo ?? null,
            'cancel_btn_info' => $cancelBtnInfo,
            'url_help' => Env::get('host.domain') . '/web/agreement/astrologer_withdraw_guide.html',
        ];

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 结算列表
     */
    public function getWithdrawalList()
    {
        $resData1 = Db::table('wechat_backup_07_18_14_43_00.zlcr_astr_account_withdrawal_record')
            ->where(['astr_id' => $this->astrInfo['id'], 'is_emergency' => 0])
            ->order('withdrawal_time desc')
            ->field("date,astr_earnings,income_tax,after_tax_income,withdrawal_time,is_withdrawal,id,1 as type,astr_earnings3")->select();
        $resData2 = Db::table('good_wechat.zyhs_astr_account_withdrawal_record')
            ->where(['astr_id' => $this->astrInfo['id'], 'type' => 1])
            ->order('withdrawal_time desc')
            ->field("id,date,astr_earnings,income_tax,after_tax_income,withdrawal_time,is_withdrawal,2 as type")->select();

        $resData = array_merge($resData1, $resData2);
        $sort = array_column($resData, 'withdrawal_time');
        array_multisort($sort, SORT_DESC, $resData);

        $withdrawalList = [];
        foreach ($resData as $key => $datum)
        {

            if ($datum['date'] < 20240101)
            {   // 当前只显示已打款数据
                $itemData = [
                    'status_des' => $datum['is_withdrawal'] == 1 ? '已打款' : '',
                    'status' => $datum['is_withdrawal'] == 1 ? 1 : 0,
                    'des_list' => [
                        '结算月份：' . date('Y-m月', strtotime($datum['date'])),
                        '结算金额：¥' . $datum['astr_earnings'],
                        '实际到账：¥' . $datum['after_tax_income'],
                        '收益来源：' . ($datum['type'] == 1 ? '问答、定制报告' : '连线咨询'),
                    ],
                ];
            } else
            {   // 当前只显示已打款数据
                $itemData = [
                    'status_des' => $datum['is_withdrawal'] == 1 ? '已打款' : '',
                    'status' => $datum['is_withdrawal'] == 1 ? 1 : 0,
                    'des_list' => [
                        '结算月份：' . date('Y-m月', strtotime($datum['date'])),
                    ],
                ];
                if (isset($datum['astr_earnings3']) && $datum['astr_earnings3'] > 0)
                {
                    $itemData['des_list'][] = '私域结算总金额：¥' . $datum['astr_earnings3'];
                }
                $itemData['des_list'][] = '结算总金额：¥' . $datum['astr_earnings'];
            }
            $withdrawalList[] = $itemData;
        }

        return show(config('code.success'), '请求成功', [
            'withdrawal_list' => $withdrawalList,
            'header_info' => $this->getWithdrawalHeaderInfo($this->astrInfo['id']),
        ]);
    }
}
